package com.fanml.service;

import com.fanml.entty.enums.MsgTypeEnum;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @title: NettyClient
 * @Author fanml
 * @describe: //TODO
 * @Date: 2021/7/4 17:20
 * @Version 1.0
 */
public class NettyClient {

    public static void nettyClientRun(String host, int port, MsgTypeEnum msgTypeEnum) {
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(workerGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true);

            bootstrap.handler(new NettyInitializerFilter<>(msgTypeEnum == MsgTypeEnum.DOWNlOAD ? new NettyClientDownloadHandle("cn_windows_7_ultimate_x64_dvd_x15-66043.iso", 3341268992L) : new NettyClientUploadHandle("F:\\新建文件夹.rar"))); // 设置过滤器
            bootstrap.remoteAddress(host, port);
            // 服务器绑定端口监听
            ChannelFuture f = bootstrap.connect().sync();
            Channel channel = f.channel();
            channel.closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}
